<!--
 * @Description: 隧道编排
 * @Author: 0001100986/LiuShuai
 * @Date: 2021-06-10 14:14:01
 * @LastEditTime: 2021-11-11 09:54:50
 * @LastEditors: 0001100986/LiuShuai
-->
<template>
  <div class="ipsc-content">
    <template v-if="show === 0">
      <table-bar
        :showTop="false"
        :columns="columns"
        @changeColumn="changeColumn"
        layout="search, column"
      >
        <div slot="top">
          <el-form :model="filterSearch" label-width="80px" label-position="right">
            <el-row :gutter="20">
              <el-col :xs="24" :sm="12" :lg="6">
                <!-- 隧道名称 -->
                <el-form-item label="隧道名称">
                  <el-input v-model.trim="filterSearch.keyword" placeholder="名称" maxlength="200"></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :lg="6">
                <!-- 租户名称 -->
                <el-form-item label="租户名称">
                  <el-input v-model.trim="filterSearch.tenantName" placeholder="名称"></el-input>
                </el-form-item>
              </el-col>
              <!-- 搜索 重置 -->
              <el-row :xs="24" :sm="12" :lg="6" style="float: right; margin-right: 10px;">
                <el-button type="primary" @click="search">搜索</el-button>
                <el-button @click="reset">重置</el-button>
              </el-row>
            </el-row>
          </el-form>
        </div>
        <div slot="bottom">
          <!-- 刷新 -->
          <el-button size="medium" @click="reset" v-power="2">刷新</el-button>
          <!-- 新增 -->
          <el-button size="medium" type="primary" plain @click="showCreate" v-power="2">新建</el-button>
        </div>
      </table-bar>
      <tao-table
        class="table-box"
        :data="dataList"
        :page="page"
        @changePage="changePage"
        :showPage="true"
        ref="table"
      >
        <!-- 详情 -->
        <el-table-column label="详情" align="center" width="80" type="expand">
          <template slot-scope="scope">
            <info :row="scope.row" />
          </template>
        </el-table-column>
        <!-- ID -->
        <el-table-column v-if="columns[0].show" align="center" width="100" label="ID" prop="id" />
        <!-- 名称 -->
        <el-table-column
          v-if="columns[1].show"
          label="名称"
          min-width="200"
          prop="userlabel"
          show-overflow-tooltip
        />
        <!-- 租户 -->
        <el-table-column
          v-if="columns[2].show"
          align="center"
          width="150"
          label="租户"
          prop="tenantName"
          show-overflow-tooltip
        />
        <!-- 类型 -->
        <el-table-column
          v-if="columns[3].show"
          align="center"
          width="100"
          label="类型"
          sortable
          prop="tunnelType"
        />
        <!-- 状态 -->
        <el-table-column v-if="columns[4].show" label="状态" align="center" width="100" prop="state">
          <template slot-scope="scope">{{scope.row.state === 'CONNECTED' ? 'UP' : 'DOWN'}}</template>
        </el-table-column>
        <!-- 优先级 -->
        <el-table-column
          v-if="columns[5].show"
          align="center"
          width="100"
          label="优先级"
          prop="extAttrs.priority"
        >
          <template slot-scope="scope">{{scope.row.extAttrs.priority === 'HIGH' ? '高' : '低'}}</template>
        </el-table-column>
        <!-- VPN -->
        <el-table-column
          v-if="columns[6].show"
          align="center"
          width="150"
          label="VPN"
          prop="vpnUserLabel"
          show-overflow-tooltip
        >
          <template slot-scope="scope">{{scope.row.enableVpn ? scope.row.vpnUserLabel : '-'}}</template>
        </el-table-column>
        <!-- 监控 -->
        <el-table-column
          v-if="columns[7].show"
          align="center"
          width="120"
          label="监控"
          prop="enableSqa"
        >
          <template slot-scope="scope">
            <el-switch
              v-power="scope.row.dgId === 100000 ? 0 : 2"
              v-model="scope.row.enableSqa"
              @change="monitorSwitch(scope.row)"
            ></el-switch>
            {{scope.row.enableSqa ? '开启' : '关闭'}}
          </template>
        </el-table-column>
        <!-- 限速 -->
        <el-table-column
          v-if="columns[8].show"
          align="center"
          width="100"
          label="限速"
          prop="rateLimit"
        >
          <template
            slot-scope="scope"
          >{{scope.row.rateLimit === 0 ? '不限速' : scope.row.rateLimit + 'Mbps'}}</template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column fixed="right" label="操作" align="center" width="150px">
          <!-- 编辑  删除-->
          <template slot-scope="scope">
            <el-button
              type="text"
              style="color: #FA6962"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
              v-power="scope.row.dgId === 100000 ? 0 : 2"
            >删除</el-button>
            <el-dropdown
              size="small"
              placement="bottom"
              trigger="click"
              v-power="scope.row.dgId === 100000 ? 0 : 2"
            >
              <span class="el-dropdown-link">
                更多
                <i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <!-- 隧道限速 -->
                <el-dropdown-item @click.native="showDialog(scope.row)">隧道限速</el-dropdown-item>
                <!-- 策略设置 -->
                <el-dropdown-item @click.native="strDialog(scope.row)">策略设置</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </tao-table>
      <!-- 隧道限速 -->
      <el-dialog
        :title="dialogTitle"
        width="500px"
        :visible.sync="dvEdit"
        :close-on-click-modal="false"
      >
        <el-form ref="ruleForm" :model="form" label-width="80px" label-position="right">
          <!-- 限速 -->
          <el-form-item label="限速" prop="speed" key="speed">
            <el-switch v-model="form.speed" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
          </el-form-item>
          <template v-if="form.speed">
            <!-- 带宽 -->
            <el-form-item
              label="带宽"
              prop="rateLimit"
              key="rateLimit"
              :rules="[
              { required: true, message: '不能为空', trigger: 'blur'},
              { type: 'number', message: '范围：1-100', min: 1, max: 100, trigger: 'blur'}
            ]"
            >
              <el-input v-model.number="form.rateLimit">
                <template slot="append">Mbps</template>
              </el-input>
            </el-form-item>
          </template>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <!--取 消  确 定-->
          <el-button @click="dvEdit = false">取消</el-button>
          <el-button type="primary" @click="onSubmit">确认</el-button>
        </span>
      </el-dialog>
      <!-- 设置策略 -->
      <str
        :tunnelInfo="tunnelInfo"
        :samgrList="samgrList"
        :dialogStr="dialogStr"
        @changeStr="changeStr($event)"
      />
    </template>
    <template v-if="show === 1">
      <create :tenants="tenants" @handleChange="handleChange($event)" />
    </template>
  </div>
</template>

<script>
import create from './create';
import info from './info';
// 设置策略
import str from './str';

export default {
  components: {
    info,
    str,
    create
  },
  data () {
    return {
      dvEdit: false,
      dialogTitle: '',
      page: {
        page: 1,
        pageSize: 15,
        total: 0
      },
      form: {
        userlabel: null,
        speed: false,
        rateLimit: 0
      },
      dataList: [],
      filterSearch: {
        keyword: null,
        tenantName: null
      },
      columns: [
        { name: 'ID', show: true },
        { name: '名称', show: true },
        { name: '租户', show: true },
        { name: '类型', show: true },
        { name: '优先级', show: true },
        { name: 'VPN', show: true },
        { name: '状态', show: true },
        { name: '监控', show: true },
        { name: '限速', show: true }
      ],
      dialogStr: false,
      samgrList: [],
      tunnelInfo: {},
      show: 0,
      tenants: []
    };
  },
  mounted () {
    let _this = this;
    _this.$nextTick(() => {
      _this.refresh();
    });
  },
  methods: {
    // 监控开关
    monitorSwitch (val) {
      let _this = this;
      let title = val.enableSqa ? '开启' : '关闭';
      _this.$http.post({
        url: '/api/sdwan/businesslayout/control/sqa',
        data: {
          tunnelId: val.id,
          enableSqa: title === '开启' ? true : false
        }
      }).then(res => {
        let { status } = res;
        if (status === '0') {
          _this.$message.success(title + '成功！');
          _this.refresh();
        } else {
          _this.refresh();
        }
      }).catch(err => {
        _this.refresh();
      });
    },
    // 回调
    handleChange (val) {
      let _this = this;
      _this.show = val;
    },
    // 获取所有策略
    strDialog (row) {
      let _this = this;
      // 显示弹框
      _this.dialogStr = true;
      // 隧道信息
      _this.tunnelInfo = row;
      // 主动端ID
      let neId = row.extAttrs.cpeNeId;
      // 隧道ID
      let tunnelId = row.id;
      _this.$http.get({
        url: '/api/sdwan/policy/getPolicyList/' + neId + '/' + tunnelId
      }).then(res => {
        let { status, resultBody } = res;
        if (status === '0') {
          let result = [];
          if (resultBody.length > 0) {
            resultBody[0].samgrList.map((item, index) => {
              if (item.jitter > 0) {
                result.push({
                  id: '编号-' + (index + 1),
                  type: 'jitter',
                  size: item.jitter === 0 ? '' : item.jitter.toString(),
                  userlabel: item.userlabel.lastIndexOf('-') > -1 ? item.userlabel.substring(0, item.userlabel.lastIndexOf('-')) : item.userlabel
                });
              }
              if (item.latency > 0) {
                result.push({
                  id: '编号-' + (index + 1),
                  type: 'latency',
                  size: item.latency === 0 ? '' : item.latency.toString(),
                  userlabel: item.userlabel.lastIndexOf('-') > -1 ? item.userlabel.substring(0, item.userlabel.lastIndexOf('-')) : item.userlabel
                });
              }
              if (item.loss > 0) {
                result.push({
                  id: '编号-' + (index + 1),
                  type: 'loss',
                  size: item.loss === 0 ? '' : item.loss.toString(),
                  userlabel: item.userlabel.lastIndexOf('-') > -1 ? item.userlabel.substring(0, item.userlabel.lastIndexOf('-')) : item.userlabel
                });
              }
            });
            _this.samgrList = result;
          } else {
            _this.samgrList = [];
          }
        }
      });
    },
    // 设置策略，回调
    changeStr (val) {
      let _this = this;
      _this.dialogStr = val;
    },
    // 搜索
    search () {
      let _this = this;
      _this.page.page = 1;
      _this.refresh();
    },
    // 重置
    reset () {
      let _this = this;
      _this.page.page = 1;
      _this.filterSearch = {
        label: null
      };
      _this.refresh();
    },
    // 刷新
    refresh () {
      let _this = this;
      let params = {
        keyword: _this.filterSearch.keyword,
        tenantName: _this.filterSearch.tenantName,
        limit: _this.page.pageSize,
        offset: (_this.page.page - 1) * _this.page.pageSize
      };
      _this.$http.post({
        url: '/api/sdwan/businesslayout/query',
        data: params
      }).then(res => {
        let { status, resultBody } = res;
        if (status === '0') {
          _this.page.total = resultBody.count;
          _this.dataList = resultBody.objects;
          _this.$emit('handleRefresh', 'ipsec');
        }
      });
    },
    // 过滤显示字段
    changeColumn (columns) {
      this.columns = columns;
      this.$refs.table.doLayout();
    },
    // 切换页码 & 显示条数
    changePage (page) {
      if (page.page) {
        this.page.page = page.page;
      } else {
        this.page.page = 1;
        this.page.pageSize = page.limit;
      }
      this.refresh();
    },
    // 显示限速弹出框
    showDialog (data) {
      let _this = this;
      _this.dvEdit = true;
      _this.$nextTick(() => {
        _this.$refs['ruleForm'].clearValidate();
      });
      _this.form = {
        id: data.id,
        userlabel: data.userlabel,
        speed: data.rateLimit === 0 ? false : true,
        rateLimit: data.rateLimit
      };
      _this.dialogTitle = _this.form.userlabel + '隧道限速';
    },
    // 隧道限速
    onSubmit () {
      let _this = this;
      _this.$refs['ruleForm'].validate(async (valid) => {
        if (valid) {
          let speed = {
            tunnelId: _this.form.id
          };
          // 判断是否限速
          if (_this.form.speed) {
            speed.rateLimit = _this.form.rateLimit;
          }
          _this.$http.post({
            url: '/api/sdwan/businesslayout/update/ratelimit',
            data: speed
          }).then(res => {
            _this.$message.success('设置成功！');
            _this.dvEdit = false;
            _this.refresh();
          });
        } else {
          _this.$message.error('请检查必填项！');
          return false;
        }
      });
    },
    // 过滤回显
    filterWan (site, ne, wan) {
      let result = [site.sitename, ne.userlabel, wan];
      return result;
    },
    // 新建隧道
    showCreate () {
      let _this = this;
      let current = _this.$store.state.user.user.info;
      let tenants = [];
      // 初始化租户集合
      if (current.dgId !== 100000) {
        tenants.push({
          value: current.dgId,
          label: current.dgName
        });
        _this.tenants = tenants;
        _this.show = 1;
      } else {
        _this.$http.post({
          url: '/api/sdwan/tenant/getMultiDg',
          data: {
            limit: 0,
            offset: 0,
            hasDefault: false
          }
        }).then(res => {
          let { status, resultBody } = res;
          if (status === '0') {
            for (let i = 0; i < resultBody.objects.length; i++) {
              tenants.push({
                value: resultBody.objects[i].id,
                label: resultBody.objects[i].userlabel
              });
            }
            _this.tenants = tenants;
            _this.show = 1;
          }
        });
      }
    },
    // 删除
    handleDelete (scope) {
      let _this = this;
      this.$confirm('您确定要删除当前数据吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        _this.$http.deleted({
          url: '/api/sdwan/businesslayout',
          data: [scope.row.id]
        }).then(res => {
          let { status } = res;
          if (status === '0') {
            _this.$message.success('删除成功！');
            _this.refresh();
          }
        });
      }).catch(() => {
        _this.$message.info('取消删除');
      });
    },
  }
};
</script>

<style lang='scss' scoped>
.ipsc-content {
  width: 100%;
  height: 100%;

  .avatar {
    width: 50px;
    height: 50px;
    border-radius: 50%;
  }
  .table-box {
    ::v-deep .el-button {
      padding: 0;
    }
    ::v-deep .el-dropdown-link {
      cursor: pointer;
      color: #409eff;
      margin-left: 5px;
    }
  }

  ::v-deep .el-dialog__body {
    padding-bottom: 0;
  }
}
</style>